﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using System.Windows.Media.Imaging;

namespace SalaryChannel
{
    public partial class PhotoUploadDialog : UserControl
    {
        /// <summary>
        /// Constructer of class Upload
        /// </summary>
        public PhotoUploadDialog()
        {
            InitializeComponent();
            thumbInitSource= this.thumb.Source;
        }

        private ImageSource thumbInitSource = null;

        private string ChannelID
        {
            get;
            set;
        }


        /// <summary>
        /// The Difinition of CompleteEvent
        /// </summary>
        public event EventHandler<System.ComponentModel.AsyncCompletedEventArgs> CompletedEvent;
        

        /// <summary>
        /// The current part being transferred
        /// </summary>
        private int partIndex;

        private int totalParts;

        /// <summary>
        /// The max transfer size.
        /// </summary>
        private readonly int transferSize = 50000;

        /// <summary>
        /// The bytes of upload photo
        /// </summary>
        private byte[] photoBytes;

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            ServiceInstance.ViewService.UploadPhotoCompleted += new EventHandler<SalaryChannel.ViewService.UploadPhotoCompletedEventArgs>(ViewService_UploadPhotoCompleted);
            ServiceInstance.ViewService.InsertPhotoCompleted += new EventHandler<SalaryChannel.ViewService.InsertPhotoCompletedEventArgs>(ViewService_InsertPhotoCompleted);
           
        }

       
        private bool _isReady = false;
        private bool IsReady
        {
            set
            {
                _isReady = value;
                if(value)
                {
                    this.Cursor = Cursors.Arrow;

                }
                else
                {
                    this.Cursor = Cursors.Wait;
                }
            }
            get
            {
                return _isReady;
            }
        }

        public void Initialize(string ChannelID,List<ViewService.VW_AlbumContains> albums)
        {
            this.ChannelID = ChannelID;
            this.thumb.Source = thumbInitSource;
            partIndex = 0;
            totalParts = 0;
            this.albumList.ItemsSource = albums;

            this.Visibility = Visibility.Visible;
            IsReady = true;
        }
       

       

        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            if (!IsReady)
            {
                return;
            }

            if (string.IsNullOrEmpty(filePath.Text)
                || string.IsNullOrEmpty(title.Text))
            {
                App.MessageBox.ShowDialog("请选择图片并设置正确的名字",
                    Title.Warning);
                return;
            }
            if (this.albumList.SelectedItem == null)
            {
                App.MessageBox.ShowDialog("请选择一个相册",
                                   Title.Warning);
                return;
            }
            try
            {

                if (photoBytes.Length % transferSize == 0)
                {
                    totalParts = photoBytes.Count() / transferSize;
                }
                else
                {
                    totalParts = photoBytes.Count() / transferSize +1;
                }

                partIndex =0;
                string photoID = Guid.NewGuid().ToString();
                int firstPartLength = totalParts ==1 ? photoBytes.Length : transferSize;
                ServiceInstance.ViewService.UploadPhotoAsync(photoBytes.Take(firstPartLength).ToArray<byte>(),
                    photoID,
                    ChannelID, photoID);
                this.loading.Show();
                IsReady = false;
            }
            catch (Exception ex)
            {

                App.MessageBox.ShowDialog("上传失败: " + ex.Message);
            }

        }
        void ViewService_UploadPhotoCompleted(object sender, SalaryChannel.ViewService.UploadPhotoCompletedEventArgs e)
        {
            try
            {
                if (e.Error !=null || e.Result==false)
                {
                    loading.Stop();
                    IsReady = true;
                    App.MessageBox.ShowDialog("上传图片失败", Title.Error);

                   
                }
                else if (partIndex + 1 == totalParts)
                {
                    ServiceInstance.ViewService.InsertPhotoAsync(title.Text, description.Text,
                        (this.albumList.SelectedItem as SalaryChannel.ViewService.VW_AlbumContains).AlbumID,
                        e.UserState.ToString(), ChannelID, App.CurrentUser.UserID);
                }

                else
                {
                    partIndex++;
                    string photoID = e.UserState.ToString();

                    if (partIndex == totalParts -1)
                    {
                        
                        ServiceInstance.ViewService.UploadPhotoAsync(photoBytes.Skip(partIndex * transferSize).Take(photoBytes.Count() % transferSize).ToArray<byte>(),
                            photoID, ChannelID,photoID);
                    }
                    else
                    {
                        ServiceInstance.ViewService.UploadPhotoAsync(photoBytes.Skip(partIndex * transferSize).Take(transferSize).ToArray<byte>(), photoID, ChannelID, photoID);
                    }
                }
            }
            catch
            {
                loading.Stop();
                IsReady = true;
                App.MessageBox.ShowDialog("上传图片失败", Title.Error);
            }
        }

        void ViewService_InsertPhotoCompleted(object sender, SalaryChannel.ViewService.InsertPhotoCompletedEventArgs e)
        {
            try
            {
                if (e.Result)
                {

                    this.thumb.Source = thumbInitSource;
                    this.filePath.Text = string.Empty;
                    this.title.Text = string.Empty;
                    this.description.Text = string.Empty;

                    if (CompletedEvent != null)
                    {
                        CompletedEvent(null, null);
                    }

                    App.MessageBox.ShowDialog("上传照片成功");
                }
                else
                {
                    App.MessageBox.ShowDialog("插入图片信息失败", Title.Error);
                }
            }
            catch
            {
                App.MessageBox.ShowDialog("插入图片信息失败", Title.Error);
            }
            finally
            {

                loading.Stop();
                IsReady = true;
            }
        }


        readonly int MaxFileLength = 1048576; //1MB
        private void cancelButton_Click(object sender, RoutedEventArgs e)
        {
            if (!IsReady)
            {
                return;
            }
            IsReady = false;

            this.albumList.ItemsSource = null;
            this.thumb.Source = null;
            this.filePath.Text = string.Empty;
            this.title.Text = string.Empty;
            this.description.Text = string.Empty;
            this.Visibility = Visibility.Collapsed;
        }

        private void chooseFileBtn_Click(object sender, RoutedEventArgs e)
        {
            if (!IsReady)
            {
                return;
            }
            IsReady = false;
            try
            {

                OpenFileDialog openFileDialog = new OpenFileDialog();
                openFileDialog = new OpenFileDialog();
                openFileDialog.Filter = "图片文件(*.jpg;*.jpeg;*.png)|*.jpg;*.jpeg;*.png|(*.jpg)|*.jpg|(*.jpeg)|*.jpeg|(*.png)|*.png";
                openFileDialog.Multiselect = false;

                if (openFileDialog.ShowDialog() == true)
                {

                    Stream uploadStrem = openFileDialog.File.OpenRead();
                    if ((int)uploadStrem.Length > MaxFileLength)
                    {
                        App.MessageBox.ShowDialog("请选择一个小于1M的图片", Title.Information);

                    }
                    if (openFileDialog.File.Name.LastIndexOf('.') != -1)
                    {
                        title.Text = openFileDialog.File.Name.Substring(0, openFileDialog.File.Name.LastIndexOf('.'));
                    }
                    else
                    {
                        title.Text = openFileDialog.File.Name;
                    }

                    filePath.Text = openFileDialog.File.Name;

                    // Fill the photobytes for upload
                    photoBytes = new byte[uploadStrem.Length + 1];
                    uploadStrem.Read(photoBytes, 0, photoBytes.Length);

                    // Fill the thumb for view
                    BitmapImage bitmap = new BitmapImage();
                    uploadStrem.Seek(0, SeekOrigin.Begin);
                    bitmap.SetSource(uploadStrem);
                    thumb.Source = bitmap;

                    uploadStrem.Close();

                }
            }
            catch (Exception ex)
            {
                App.MessageBox.ShowDialog(ex.Message, Title.Error);
            }
            finally
            {
                IsReady = true;
            }
        }

     
    }

   
}
